package com.hxk.demo.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hxk.demo.constants.Constant;
import com.hxk.demo.dto.EcgAnalysisDTO;
import com.hxk.demo.service.EcgServiceI;
import com.hxk.demo.utils.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author lyl
 */
@Slf4j
@Service
public class EcgServiceImpl implements EcgServiceI {

    @Resource
    private RestTemplate restTemplate;

    @Value("${channelId}")
    private String channelId;

    @Value("${secretKey}")
    private String secretKey;

    @Value("${baseUrl}")
    private String baseUrl;

    @Value("${accessTokenUrl}")
    private String accessTokenUrl;

    @Value("${ecgUrl}")
    private String ecgUrl;


    @Override
    public void getAccessToken() {
        Long timestamp = System.currentTimeMillis() / 1000;
        // 验证签名
        String sign = Md5Util.md5Encrypt32Lower(channelId + timestamp + secretKey);

        JSONObject paramObject = JSONUtil.createObj()
                .set("channelId", channelId)
                .set("timestamp", timestamp)
                .set("sign", sign);
        log.info("获取accessToken请求参数：{}", JSONUtil.toJsonStr(paramObject));
        JSONObject resObject = restTemplate.postForObject(baseUrl + accessTokenUrl, paramObject, JSONObject.class);
        log.info("获取accessToken返回结果：{}", JSONUtil.toJsonStr(resObject));

        if (null != resObject && resObject.getInt("code") == 0) {
            JSONObject data = resObject.getJSONObject("data");
            Constant.ACCESS_TOKEN = data.getStr("accessToken");
        }
    }

    @Override
    public JSONObject analysis(EcgAnalysisDTO dto) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "multipart/form-data");
        headers.add("accessToken", Constant.ACCESS_TOKEN);

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        try {
            ByteArrayResource byteArrayResource = new ByteArrayResource(dto.getEcgFile().getBytes()) {
                @Override
                public long contentLength() {
                    return dto.getEcgFile().getSize();
                }

                @Override
                public String getFilename() {
                    return dto.getEcgFile().getOriginalFilename();
                }
            };
            params.add("EcgFile", byteArrayResource);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("异常：{}", e.getMessage());
            return JSONUtil.createObj().set("ok", false).set("code", 4103).set("msg", "参数错误");
        }

        HttpEntity requestEntity = new HttpEntity<>(params, headers);
        JSONObject resObject = restTemplate.postForObject(baseUrl + ecgUrl, requestEntity, JSONObject.class);
        log.info("返回结果：{}", JSONUtil.toJsonStr(resObject));
        return resObject;
    }
}
